import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { Modal, Button, Tag, Space, message, Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Action, AuthButton, SearchForm, TableCard } from 'components';
import { http } from 'libs';
import store from './store';
import routes from "@/routes";


export default observer(function () {
  const [auths, setAuths] = useState([]);

  useEffect(() => {
    setAuths(getAuthData())
  }, [])

  function getAuthData() {
    let arr = []
    routes.map(route => {
      route.auth && arr.push({ auth: route.auth, title: route.title })
      // if (route.actions) {
      //   route.actions.map(action => action.auth && arr.push({auth: action.auth, title: action.title}))
      // }
      if (route.child) {
        route.child.map(page => {
          page.auth && arr.push({ auth: page.auth, title: page.title })
          // if (page.actions) {
          //   page.actions.map(action => action.auth && arr.push({auth: action.auth, title: action.title}))
          // }
        })
      }

    })
    return arr
  }

  const columns = [{
    title: 'No.',
    key: 'series',
    width: 50,
    render: (_, __, index) => <span className="idx">{index + 1}</span>
  }, {
    title: '角色',
    dataIndex: 'name',
    width: 110
  }, {
    title: '权限',
    dataIndex: 'permissions',
    render: permissions => <Space wrap>
      {
        auths.map((v, i) => {
            if (permissions.includes(v.auth)) return <Tag key={i} color="blue">{v.title}</Tag>
          }
        )
      }
    </Space>
  }, {
    title: '操作',
    width: 120,
    render: info => (
      <Action>
        <Action.Button onClick={() => store.showForm(info)}>编辑</Action.Button>
        <Action.Button onClick={() => handleDelete(info)} danger>删除</Action.Button>
      </Action>
    )
  }]

  function handleDelete(info) {
    Modal.confirm({
      title: '删除确认',
      content: `确定要删除【${info['name']}】?`,
      onOk: () => {
        return http.delete('/api/user/role/', { params: { id: info.id } })
          .then(() => {
            message.success('删除成功');
            store.fetchRecords()
          })
      }
    })
  }

  return (
    <TableCard
      title="用户权限组"
      rowKey="id"
      bordered
      loading={store.fetching}
      dataSource={store.dataSource}
      columns={columns}
      pagination={{
        showSizeChanger: true,
        showLessItems: true,
        hideOnSinglePage: true,
        showTotal: (total, range) => `第 ${range[0]} - ${range[1]} 条，共 ${total} 条`,
        pageSizeOptions: ['10', '20', '50', '100']
      }}
      onReload={store.fetchRecords}
      actions={[
        <Input value={store.f_name} onChange={store.eSet('f_name')} placeholder="请输入关键字搜索" />,
        <AuthButton type="primary" icon={<PlusOutlined />} onClick={() => store.showForm()}>新建</AuthButton>,
      ]} />
  )
})
